const isFunction = fn => typeof fn === 'function';

function _Promise (fn) {
	if(isFunction(fn) == false){
		throw new Error('参数必须是 function 类型')
	}
	
	this.state = 'pending';
	this.value = undefined
	this.onResolveList = [];
	this.onRejectList = [];
	fn(this._resolve.bind(this), this._reject.bind(this));
}

_Promise.prototype._resolve = function (val) {

	if(this.state === 'pending') this.state = 'resolved';
	else if(this.state === 'resolved' || this.state === 'rejected') return;
	else throw new Error('state 为错误的状态');
	
	this.value = val;
	this.onResolveList.forEach(fn => {
		fn()
	})
	
	return this;
}

_Promise.prototype._reject = function (val) {

	if(this.state === 'pending') this.state = 'rejected';
	else if(this.state === 'resolved' || this.state === 'rejected') return;
	else throw new Error('state 为错误的状态');
	
	this.value = val;

	return this;
}

_Promise.prototype.then = function (onResolve, onReject) {
	let next;
	 switch (this.state) {
	    // 当状态为pending时，将then方法回调函数加入执行队列等待执行
	    case 'pending':
	      this.onResolveList.push(onResolve)
	      this.onRejectList.push(onReject)
		  return this;
	      break
	    // 当状态已经改变时，立即执行对应的回调函数
	    case 'resolved':
		  console.log(this.state)
	      next = onResolve(this.value)
	      break
	    case 'rejected':
	      next = onRejected(this.value)
	      break
	  }
	  
	  
	  if(next && next.__proto__ === _Promise.prototype){
		  return next;
	  }else{
		  return new _Promise(function (res, rej) {
			res(next)
		  })
	  }
}

_Promise.prototype.catch = function (onReject) {
	if(isFunction(onReject)){
		this.onRejectList.push(onReject);
	}
}